import { useState, useRef, useEffect } from 'react'
import { Form, Input, Button, message, Select, Modal } from 'antd';
import VerificationCodeInput from '@/components/VerificationCodeInput';
import PhoneCodeInput from '@/components/PhoneCodeInput/index'
import { SAVE_LOGIN_INFO } from '@/reducers/common';
import { dispatchWithPromise, getFirstPermission } from '@/utils/util';
import { useNavigate } from 'react-router-dom';
import Style from './index.less';
import LoginWrap from '@/components/LoginWrap';
import { login, loginForMobile } from '@/apis/user/index';
import IconBox from "@/pages/login/IconBox";
import icon_password from '@/assets/image/icon-password.png'
import project_logo from '@/assets/image/project_logo.png'
import icon_user from '@/assets/image/icon-user.png'
import icon_code from '@/assets/image/icon-code.png'
import config from '../../../config.default'
import { getVerifyCode } from '@/apis/getVerifyCode';
import menuData from '@/layouts/SiderMenu/menuData';

const LoginPage = () => {
	const navigate = useNavigate();
	const [form] = Form.useForm();
	const codeRefs = useRef<{ getCodeUrl: () => void, imgKey: string }>();
	const [submitting, setSubmitting] = useState(false);
	const [loginSatusVisible, setloginSatusVisible] = useState(false)//账号选择框
	const [LoginStatus, setLoginStatus] = useState(0)//登陆 默认为密码登陆 1为验证码登录 2位忘记密码
	const [loginSelectValue, setloginSelectValue] = useState('')
	const [loginSelectFormValue, setloginSelectFormValue] = useState<UserLoginParam & UserMobileCodeLoginParam>({
		loginName: '',
		password: '',
		imgKey: '',
		mobile: '',
		verifyCode: '',
		imgCode: ""
	})
	const [multiAccountList, setmultiAccountList] = useState<string[]>([])
	async function submitHandle(values: UserLoginParam & UserMobileCodeLoginParam) {
		setSubmitting(true);
		values.imgKey = codeRefs.current?.imgKey || '';
		try {
			//用户密码登录
			if (LoginStatus === 0) {
				const res = await login(values)
				dispatchWithPromise({ type: SAVE_LOGIN_INFO, data: res.data })
				let url = await getFirstPermission(menuData)
				navigate(url);
			}
			if (LoginStatus === 1) {
				const res = await loginForMobile(values)
				//如果checkAccountFlag为true就跳转选择账号框
				if (res.data.checkAccountFlag && res.data.multiAccountList) {
					setloginSelectFormValue(values)
					setmultiAccountList(res.data.multiAccountList)
					setloginSelectValue(res.data.multiAccountList[0])
					setloginSatusVisible(true)
					return
				} else {
					dispatchWithPromise({ type: SAVE_LOGIN_INFO, data: res.data })
				}
				let url = await getFirstPermission(menuData)
				navigate(url);
			}
		} finally {
			setSubmitting(false)
			codeRefs.current?.getCodeUrl()
		}
	}
	//获取手机号
	async function getPhoneCode() {
		let phone = form.getFieldValue('mobile') as string
		if (!phone) {
			message.error('请输入手机号')
			return false
		}
		try {
			await getVerifyCode({ mobile: phone, type: "b_login_verify_code" })
			message.success('获取验证码成功')
			return true
		} catch (e) {
			return false
		}
	}
	//忘记密码
	function onForgetBtn() {
		navigate('/forgetPwd')
	}
	//选中用户登陆
	async function onSelectUserLogin() {
		let res = await loginForMobile({ ...loginSelectFormValue, loginName: loginSelectValue })
		dispatchWithPromise({ type: SAVE_LOGIN_INFO, data: res.data })
		let url = await getFirstPermission(menuData)
		navigate(url);

	}
	useEffect(() => {
		Modal.destroyAll()
	}, [])
	return (
		<LoginWrap>
			{
				loginSatusVisible ?
					<div className={Style.login_status_form}>
						<div className={Style.login_status_form_title}>请选择您的登录账户</div>
						<div>
							<Select placeholder='请选择账户'
								style={{ width: "100%", marginBottom: '24px', height: '46px' }}
								value={loginSelectValue}
								onChange={e => setloginSelectValue(e)}
								options={multiAccountList.map(item => ({ label: item || '', value: item }))}></Select>
						</div>
						<Button type="primary" style={{ width: "100%", height: '44px' }} onClick={onSelectUserLogin}>确认</Button>
					</div>
					: <>
						<div className={Style.login_form_top}>
							<img src={project_logo} alt='' />
							<div className={Style.defaultTitle}>{config.layout.defaultTitle}</div>
						</div>
						<div className={Style.login_textWrap}>
							<div className={Style.login_text + ' ' + (LoginStatus == 0 ? Style.loginStatusActive : null)} onClick={() => setLoginStatus(0)} >
								账户密码登录
							</div>
							<div className={Style.login_text + ' ' + (LoginStatus == 1 ? Style.loginStatusActive : null)} onClick={() => setLoginStatus(1)}>
								验证码登录
							</div>
						</div>
						<Form layout="vertical" form={form} className={Style.form} onFinish={submitHandle}>
							{
								LoginStatus == 0 ?
									<>
										<Form.Item name="loginName" rules={[{ required: true, message: '请输入用户名' },
										{ min: 4, max: 16, message: "用户账号长度为4-30位" }]}>
											<Input size="large" placeholder="请输入用户名" prefix={<IconBox icon={icon_user} />} />
										</Form.Item>
										<Form.Item name="password" rules={[{ required: true, message: '请输入密码' },
										{ max: 20, message: "最大不超过20位" },
										{ pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\w]{8,}$/, message: '密码至少8个字符，且必须包含字母和数字' }]}>
											<Input.Password type="password" size="large" placeholder="请输入密码" prefix={<IconBox icon={icon_password} />} />
										</Form.Item>
										<Form.Item name="imgCode" rules={[{ required: true, message: '请输入验证码' }]}>
											<VerificationCodeInput ref={codeRefs} size="large" placeholder="请输入验证码" Icon={<IconBox icon={icon_code} />} />
										</Form.Item>
									</> :
									<>
										<Form.Item name="mobile" rules={[{ required: true, message: '请输入手机号' }]}>
											<Input size="large" maxLength={11} placeholder="请输入手机号" prefix={<IconBox icon={icon_user} />} />
										</Form.Item>
									</>
							}

							{
								LoginStatus == 1 ?
									<Form.Item name="verifyCode" rules={[{ required: true, message: '请输入手机号验证码' }]} >
										<PhoneCodeInput getPhoneCode={getPhoneCode} prefix={<IconBox icon={icon_code} />} />
									</Form.Item>
									: null
							}
							<Form.Item style={{ textAlign: "right" }}>
								<Button type='link' onClick={onForgetBtn}>忘记密码?</Button>
							</Form.Item>
							<Button htmlType="submit" loading={submitting} style={{ fontSize: "16px" }} type="primary" block size="large" >登录</Button>
						</Form>
					</>
			}
		</LoginWrap>
	)
}
export default LoginPage